// utils/examUtils.ts
import { ExamPaperResponse, ExamRecord } from './examTypes';
import { IAppOption } from '../../typings/index';

/**
 * 考试相关工具函数
 */
export class ExamUtils {
  /**
   * 去除HTML标签
   * @param html 包含HTML标签的字符串
   * @returns 清理后的纯文本
   */
  static stripHtmlTags(html: string): string {
    if (html == null) {
      return '';
    }
    return html.replace(/<[^>]+>/g, '');
  }

  /**
   * 计算进度
   * @param currentIndex 当前索引
   * @param total 总数
   * @returns 格式化的进度字符串 (例: "1/10")
   */
  static calculateProgress(currentIndex: number, total: number): string {
    return (currentIndex + 1) + "/" + total;
  }

  /**
   * 从网络获取题目列表
   * @param recordId 记录ID
   * @param paperId 试卷ID
   * @returns 试卷和题目列表
   */
  static async fetchQuestionList(recordId: number, paperId: number): Promise<ExamPaperResponse> {
    const app = getApp<IAppOption>();
    
    return new Promise((resolve, reject) => {
      wx.request({
        url: app.buildApiUrl('/api/paper-questions/question-list'),
        method: 'GET',
        header: {'Authorization': wx.getStorageSync('token')},
        data: { recordId, paperId },
        success: (res) => {
          if (res.statusCode === 200) {
            resolve(res.data as ExamPaperResponse);
          } else {
            reject(new Error(`请求失败，状态码: ${res.statusCode}`));
          }
        },
        fail: (err) => {
          reject(err);
        }
      });
    });
  }

  /**
   * 记录答案
   * @param recordId 记录ID
   * @param paperId 试卷ID
   * @param questionId 问题ID
   * @param userAnswer 用户答案
   * @param isCorrect 是否正确
   * @param spentTime 花费时间
   * @returns 是否成功
   */
  static async answer(recordId: number, paperId: number, questionId: number,
    userAnswer: string, isCorrect: number, spentTime: number): Promise<Boolean> {
    const app = getApp<IAppOption>();

    return new Promise((resolve, reject) => {
      wx.request({
        url: app.buildApiUrl('/api/exam/answer'),
        method: 'POST',
        header: {'Authorization': wx.getStorageSync('token')},
        data: {
          recordId,
          paperId,
          questionId,
          userAnswer,
          isCorrect,
          spentTime
        },
        success: (res) => {
          if (res.statusCode === 200) {
            resolve(res.data.code === 200)
          } else {
            reject(new Error(`请求失败，状态码: ${res.statusCode}`));
          }
        },
        fail: (err) => {
          reject(err);
        }
      });
    });
  }

  /**
   * 结束考试
   * @param paperId 试卷ID
   * @param recordId 记录ID
   * @returns 考试记录
   */
  static async examFinish(paperId: number, recordId: number): Promise<ExamRecord> {
    const app = getApp<IAppOption>();

    return new Promise((resolve, reject) => {
      wx.request({
        url: app.buildApiUrl('/api/exam/finish'),
        method: 'POST',
        header: {'Authorization': wx.getStorageSync('token')},
        data: { paperId, recordId },
        success: (res) => {
          if (res.statusCode === 200) {
            resolve(res.data.data as ExamRecord);
          } else {
            reject(new Error(`请求失败，状态码: ${res.statusCode}`));
          }
        },
        fail: (err) => {
          reject(err);
        }
      });
    });
  }

  /**
   * 获取选项状态
   * @param question 问题对象
   * @param option 选项对象
   * @returns 选项状态 ('correct'|'incorrect'|'')
   */
  static getOptionStatus(question: any, option: any): string {
    if (!question.userAnswer) return ''; // 未选择
    if (option.optionNo === question.correctAnswer) return 'correct'; // 正确答案
    if (option.optionNo === question.userAnswer) return 'incorrect'; // 用户选择的错误答案
    return '';
  }

  /**
   * 解析包含Markdown图片的内容，生成混合的文本和图片数组
   * @param content 包含Markdown图片的内容
   * @returns 混合的文本和图片数组
   */
  static parseContentWithImages(content: string): Array<{type: 'text' | 'image', content: string}> {
    if (!content) return [];
    
    const result: Array<{type: 'text' | 'image', content: string}> = [];
    // 匹配Markdown图片语法: ![alt](url)
    const parts = content.split(/(!\[.*?\]\(.*?\))/g);

    const config=getApp().globalConfig.config;

    parts.forEach(part => {
      if (part.startsWith('![') && part.includes('](') && part.endsWith(')')) {
        // 提取图片URL
        const urlMatch = part.match(/!\[.*?\]\((.*?)\)/);
        if (urlMatch && urlMatch[1]) {
          const url=urlMatch[1].startsWith('http')?urlMatch[1]:`${config.baseUrl}${urlMatch[1]}`;
          // console.log('urlMatch[1]:'+urlMatch[1])
          // console.log('url:'+url)
          
          // debugger
          result.push({
            type: 'image',
            content: url
          });
        }
      } else if (part) {
        // 文本内容
        result.push({
          type: 'text',
          content: part
        });
      }
    });
    
    return result;
  }

  /**
   * 收藏题目
   * @param questionId 题目ID
   * @param recordId 记录ID
   * @param paperId 试卷ID
   * @param favorite 是否收藏
   * @returns 收藏结果
   */
  static async favoriteQuestion(questionId: number, recordId: number, paperId: number, favorite: boolean): Promise<any> {
    const app = getApp<IAppOption>();
    
    return new Promise((resolve, reject) => {
      wx.request({
        url: app.buildApiUrl('/api/user/favorite-questions'),
        method: 'POST',
        header: {
          'Authorization': wx.getStorageSync('token'),
          'Content-Type': 'application/json'
        },
        data: {
          userId: wx.getStorageSync('userId'),
          questionId: questionId,
          recordId: recordId,
          paperId: paperId,
          actionType: favorite ? 1 : 0, // 1表示收藏，0表示取消收藏
          remark: favorite ? "用户收藏该题目" : "用户取消收藏该题目"
        },
        success: (res) => resolve(res),
        fail: (err) => reject(err)
      });
    });
  }

  /**
   * 提交题目异议
   * @param questionId 题目ID
   * @param recordId 记录ID
   * @param paperId 试卷ID
   * @param remark 异议说明
   * @returns 提交结果
   */
  static async reportQuestionIssue(questionId: number, recordId: number, paperId: number, remark: string): Promise<any> {
    const app = getApp<IAppOption>();
    
    return new Promise((resolve, reject) => {
      wx.request({
        url: app.buildApiUrl('/api/user/favorite-questions'),
        method: 'POST',
        header: {
          'Authorization': wx.getStorageSync('token'),
          'Content-Type': 'application/json'
        },
        data: {
          userId: wx.getStorageSync('userId'),
          questionId: questionId,
          recordId: recordId,
          paperId: paperId,
          actionType: 2, // 2表示异议
          remark: remark
        },
        success: (res) => resolve(res),
        fail: (err) => reject(err)
      });
    });
  }
}